package de.ifgi.tank;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import android.util.Log;

/**
 * This Class provides the UDP sending functionality of the App. It creates an
 * UDP Packet and sends it to the designated IP and Port
 * 
 * @author d.wilhelm@wwu.de
 * @author g.pape@wwu.de
 * 
 */

public class UDPSend {

	private static String prefix = "ifgi-tank:";

	private InetAddress targetHost;
	private int port;
	private DatagramSocket dsocket;

	public UDPSend(InetAddress address, int port) throws SocketException {
		this.targetHost = address;
		this.port = port;

	}

	private boolean send(byte[] message) {
		try {
			Log.i("udp_send", targetHost.getHostAddress(), null);

			DatagramPacket packet = new DatagramPacket(message, message.length,
					targetHost, port);

			// Create a datagram socket, send the packet through it, close it.
			dsocket = new DatagramSocket();
			dsocket.send(packet);
			dsocket.disconnect();
			dsocket.close();
			return true;
		} catch (Exception e) {
			System.err.println(e);
			return false;
		}
	}

	/**
	 * Does nothing
	 */
	public void openSocket() {
	}

	/**
	 * Closes the socket
	 */
	public void closeSocket() {
		dsocket.close();
	}

	/**
	 * Initializes the upd sending progress with the values for the left and
	 * right engine
	 * 
	 * @param leftVal
	 * @param rightVal
	 * @param reverse
	 * @param spin
	 * @return true if the operation was successful, else false
	 */
	public boolean sendCommand(int leftVal, int rightVal, boolean reverse,
			boolean spin) {
		String send = prefix + String.format("%04d", leftVal) + ";"
				+ String.format("%04d", rightVal) + ";";
		if (reverse) {
			send += "r";
		} else {
			send += "f";
		}
		send += ";";
		if (spin) {
			send += "s";
		} else {
			send += "f";
		}
		Log.i("sendCommand", send);
		return this.send(send.getBytes());
	}

}
